package com.qding.park.adapter.bsg.adapter.impl;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.qding.park.adapter.bsg.adapter.config.BSGConfig;
import com.qding.park.adapter.bsg.adapter.constant.ConstantFunction;
import com.qding.park.adapter.bsg.adapter.entity.ResponseMsg;
import com.qding.park.adapter.bsg.adapter.enums.ErrorCodeEnum;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.system.NetWorkException;
import com.qding.park.common.core.network.HttpUtil;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.target.common.adapter.ParkAdapter;
import com.qding.park.target.common.entity.AdParkConnStatu;
import com.qding.park.target.common.entity.AdParkInfo;
import com.qding.park.target.common.entity.AdcarInParkTag;
import com.qding.park.target.common.enums.ParkConnStatuEnum;

//@Component("bsg.parkAdapter")
/**
 * @ClassName ParkAdapterImpl
 * @Description TODO(车场实现)
 * @author Administrator
 * @Date 2016年8月28日 下午9:46:53
 * @version 1.0.0
 */
@Service("parkAdapter_12")
public class ParkAdapterImpl  implements ParkAdapter{
	
	private static final Log _log = LogFactory.getLog(ParkAdapterImpl.class);
	
	public ParkAdapterImpl(String url){
	}
	
	public ParkAdapterImpl(){
    }
	
	/* (非 Javadoc)
	 * Description:
	 * @see com.qding.park.target.common.adapter.ParkAdapter#getTempStopNum(java.lang.String)
	 * 根据车场id 返回临停车位数
	 */
	@Override
	public AdParkInfo getTempStopNum(String parkId,String userId) throws NetWorkException, AdapterException {
		String url = BSGConfig.getAdapterUrl();
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("clientID", parkId);
		Map<String, String> params = new HashMap<String, String>();
		params.put("UserID", "110");
		params.put("RequestFun", ConstantFunction.Parking_GetParkingArea);
		params.put("RequestData", jsonObj.toJSONString());
		params.put("Sign", "ddd");
		try {
			_log.info("adapter request:"+params);
			String result = HttpUtil.doPost(url, params);
			_log.info("adapter response:"+result);
			java.io.Reader in = new StringReader(result);
			Document doc = (new SAXBuilder()).build(in);

			String temp = doc.getRootElement().getValue();
			in.close();
			ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
			String errorCode=repmsg.getErrorCode();
			if(!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)){
				throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(),null,
						ExceptionMessage.createExceptionMessage(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(),
								repmsg.getErrorMsg(), ConstantFunction.Parking_GetParkingArea+" adpater处理出错 :"+repmsg.getErrorMsg()));
			}
			//{"result":{"areaName":"八卦岭四区停车场","areaTotal":"50","areaRemain":"49"}
			JSONObject data = (JSONObject)repmsg.getResult();
			int areaRemain=Integer.valueOf(data.getString("areaRemain"));
			int areaTotal=Integer.valueOf(data.getString("areaTotal"));
			AdParkInfo  parkInfo=new AdParkInfo();
			parkInfo.setRestSpace(areaRemain);
			parkInfo.setTotalSpace(areaTotal);
			return parkInfo;
			
		} catch (NetWorkException e) {
			throw e;
		}catch(AdapterException e){
			throw e;
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


//	@Override
//	public List<ApPark> queryParkConnStatus(String paramStr) throws NetWorkException, AdapterException {
//		String url = BSGConfig.getAdapterUrl();
//		JSONObject jsonObj = new JSONObject();
//		jsonObj.put("clientID", paramStr);
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("UserID", "110");
//		params.put("RequestFun", ConstantFunction.Parking_ParkingClientInfo);
//		params.put("RequestData", jsonObj.toJSONString());
//		params.put("Sign", "ddd");
//		try {
//			_log.info("adapter request:"+params);
//			String result = HttpUtil.doPost(url, params);
//			_log.info("adapter response:"+result);
//			java.io.Reader in = new StringReader(result);
//			Document doc=doc = (new SAXBuilder()).build(in);
//
//			String temp = doc.getRootElement().getValue();
//			in.close();
//			ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
//			String errorCode = repmsg.getErrorCode();
//			JSONObject data=(JSONObject) repmsg.getResult();
//			if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
//				throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
//						ExceptionMessage.createExceptionMessage(
//								AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
//								ConstantFunction.Parking_ParkingClientInfo + " adpater处理出错: "+repmsg.getErrorMsg()+",parkCode="+paramStr));
//			}
//			String text=data.getString("data");
//			List<ApPark> resultInfos=ResponseParser.parking_ParkingClientInfo(text);
//			return resultInfos;
//		} catch (AdapterException e) {
//			throw e;
//		}  catch (Exception e) {
//			throw new RuntimeException(e);
//		}
//	}

    @Override
    public AdcarInParkTag carInParkTag(String carNum, String parkCode,String userId) {
        AdcarInParkTag  inParkTag=new AdcarInParkTag();
        inParkTag.setInOutFlag(false);
        return inParkTag;
    }

    @Override
    public AdParkConnStatu getParkConnStatu(String parkCode,String userId) {
        String url = BSGConfig.getAdapterUrl();
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("clientID", parkCode);
        Map<String, String> params = new HashMap<String, String>();
        params.put("UserID", "110");
        params.put("RequestFun", ConstantFunction.Parking_ParkingClientInfo);
        params.put("RequestData", jsonObj.toJSONString());
        params.put("Sign", "ddd");
        try {
            _log.info("adapter request:"+params);
            String result = HttpUtil.doPost(url, params);
            _log.info("adapter response:"+result);
            java.io.Reader in = new StringReader(result);
            Document doc=doc = (new SAXBuilder()).build(in);

            String temp = doc.getRootElement().getValue();
            in.close();
            ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
            String errorCode = repmsg.getErrorCode();
            JSONObject data=(JSONObject) repmsg.getResult();
            if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        ExceptionMessage.createExceptionMessage(
                                AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
                                ConstantFunction.Parking_ParkingClientInfo + " adpater处理出错: "+repmsg.getErrorMsg()+",parkCode="+parkCode));
            }
            String text=data.getString("data");
            org.dom4j.Document dataDoc = DocumentHelper.parseText(text);
            Element root = dataDoc.getRootElement();
            Element  clientInfo= (Element)root.selectSingleNode("parkingClientInfo");
//            JSONObject  parkingClientInfo=  jsonobj.getJSONObject("result").getJSONObject("parkingClientInfo");
            String clientID=clientInfo.selectSingleNode("clientID").getText();
            String connState=clientInfo.selectSingleNode("connState").getText();
            String lastRequestTime=clientInfo.selectSingleNode("lastRequestTime").getText();
            AdParkConnStatu  connStatu=new AdParkConnStatu();
            connStatu.setParkCode(clientID);
            connStatu.setConnStatu("0".equals(connState)?ParkConnStatuEnum.OFF_LINE:ParkConnStatuEnum.ON_LINE);
            connStatu.setLastRequestTime(StringUtils.isBlank(lastRequestTime)?null:DateUtils.parseDate(lastRequestTime, DateUtils.DATE_LONG_DATE));
            return connStatu;
        } catch (AdapterException e) {
            throw e;
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
	
	
}
